//
//  YCConnectViewController.m
//  lianganyuchu
//
//  Created by iMac on 17/3/1.
//  Copyright © 2017年 杭州桑缇电子商务有限公司. All rights reserved.
//

#import "YCConnectViewController.h"
#define YCPrintCellIdentify @"YCPrintTableViewCell"

#define IMG_SIZE 120
@interface YCConnectViewController ()
{
    UITableView *m_tableView;
    UIButton *m_btnSearch;
    
    UIView *m_unlinkedView;
    UIView *m_linkedView;
    
    UIButton *m_btnBound;
    UIImageView *m_connectedView;
    UILabel *m_labelCancel;
    
    UIView *m_headerView;
    UIButton *m_selectedBtn;
}
@end

@implementation YCConnectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem=[self tbarBackButton];
    
    
    [self.view setBackgroundColor:WHITE_COLOR];
    _connectedDevices = [NSMutableArray array];
    _deviceArray=[NSMutableArray array];
    [self addMainView];
    
    NSUserDefaults  *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *uuidString = [userDefault stringForKey:@"uuidstring"];
    NSString *status=[userDefault stringForKey:@"printOn"];
    
    if ( (uuidString.length>0) && [status isEqualToString:@"yes"]) {
        self.navigationItem.title=@"已连接";
        [self showLinkedView];
    }else{
        self.navigationItem.title=@"搜索设备";
        [self addSearchView];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self loadDevices];
    });
}
-(void)addSearchView
{
    if (m_unlinkedView==nil) {
        m_unlinkedView=[[UIView alloc]initWithFrame:CGRectMake(0, kNAV_HEIGHT, kMainScreen_Width, kMainPage_Height)];
        [m_unlinkedView setBackgroundColor:WHITE_COLOR];
    }
    [self.view addSubview:m_unlinkedView];
    
    UILabel *labelTitle=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, kMainScreen_Width*0.8, 20)];
    [labelTitle setTextAlignment:NSTextAlignmentCenter];
    [labelTitle setText:@"正在搜索打印机"];
    [labelTitle setTextColor:TEXT_DEEP];
    [labelTitle setFont:[UIFont LightFontOfSize:20]];
    [m_unlinkedView addSubview:labelTitle];
    [labelTitle setCenter:CGPointMake(kMainScreen_Width*0.5, 50+10)];
    
    UILabel *labelDesc=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, kMainScreen_Width*0.8, 45)];
    [labelDesc setTextAlignment:NSTextAlignmentCenter];
    [labelDesc setNumberOfLines:2];
    [labelDesc setText:@"请确认打印机电源已开启\n并在手机附近"];
    [labelDesc setTextColor:TEXT_LIGHT];
    [labelDesc setFont:[UIFont LightFontOfSize:16]];
    [m_unlinkedView addSubview:labelDesc];
    [labelDesc setCenter:CGPointMake(kMainScreen_Width*0.5, CGRectGetMaxY(labelTitle.frame)+20+kDistance)];
    
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 120, 104)];
    [imgView setContentMode:UIViewContentModeScaleAspectFit];
    [imgView setImage:[UIImage imageNamed:@"print_unlink"]];
    [m_unlinkedView addSubview:imgView];
    [imgView setCenter:CGPointMake(kMainScreen_Width*0.5, CGRectGetMaxY(labelDesc.frame)+104/2+50)];
    
}
-(void)showLinkedView
{
    if (m_linkedView==nil) {
        m_linkedView=[[UIView alloc]initWithFrame:CGRectMake(0, kNAV_HEIGHT, kMainScreen_Width, kMainPage_Height)];
        [m_linkedView setBackgroundColor:getUIColor(0xffffff)];
    }
    [self.view addSubview:m_linkedView];
    
    UILabel *labelTitle=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, kMainScreen_Width*0.8, 20)];
    [labelTitle setTextAlignment:NSTextAlignmentCenter];
    [labelTitle setText:@"已经连接佳博打印机"];
    [labelTitle setTextColor:TEXT_DEEP];
    [labelTitle setFont:[UIFont LightFontOfSize:20]];
    [m_linkedView addSubview:labelTitle];
    [labelTitle setCenter:CGPointMake(kMainScreen_Width*0.5, 50+10)];
    
    UILabel *labelDesc=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, kMainScreen_Width*0.8, 20)];
    [labelDesc setTextAlignment:NSTextAlignmentCenter];
    [labelDesc setText:@"状态：正常"];
    [labelDesc setTextColor:TEXT_DEEP];
    [labelDesc setFont:[UIFont LightFontOfSize:16]];
    [m_linkedView addSubview:labelDesc];
    [labelDesc setCenter:CGPointMake(kMainScreen_Width*0.5, CGRectGetMaxY(labelTitle.frame)+10+kDistance)];
    
    UIImageView *linkImg=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 116, 120)];
    [linkImg setCenter:CGPointMake(kMainScreen_Width*0.5, CGRectGetMaxY(labelDesc.frame)+kCellHeight+120/2)];
    [linkImg setImage:[UIImage imageNamed:@"print_link"]];
    [m_linkedView addSubview:linkImg];
    
    m_btnBound=[[UIButton alloc]initWithFrame:CGRectMake(kDistance, kMainScreen_Height-60-44-kNAV_HEIGHT, kMainScreen_Width-2*kDistance, 44)];
    [m_btnBound.titleLabel setFont:[UIFont LightFontOfSize:18]];
    [m_btnBound setBackgroundColor:MAIN_COLOR];
    [m_btnBound setTitle:@"重新绑定" forState:UIControlStateNormal];
    [m_btnBound addTarget:self action:@selector(refreshDeviceList:) forControlEvents:UIControlEventTouchUpInside];
    m_btnBound.layer.cornerRadius=5.0f;
    [m_linkedView addSubview:m_btnBound];
}
-(void)loadDevices
{
    SEPrinterManager *_manager = [SEPrinterManager sharedInstance];
    [_manager startScanPerpheralTimeout:5 Success:^(NSArray<CBPeripheral *> *perpherals,BOOL isTimeout) {
        self.title=@"搜索中";
        _deviceArray = [NSMutableArray arrayWithArray:perpherals];
        [m_unlinkedView setHidden:YES];
        [m_tableView reloadData];
    } failure:^(SEScanError error) {
        NSLog(@"%ld",(long)error);
    }];
}
-(void)refreshDeviceList:(id)sender
{
    self.title=@"搜索中";
    [m_linkedView setHidden:YES];
    [self loadDevices];
}
-(void)addMainView
{
    CGFloat width=kMainScreen_Width-2*kDistance;
    m_tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, kMainScreen_Width, kMainScreen_Height)];
    m_tableView.delegate=self;
    m_tableView.dataSource=self;
    [self.view addSubview:m_tableView];
    m_tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [m_tableView registerNib:[UINib nibWithNibName:YCPrintCellIdentify bundle:nil] forCellReuseIdentifier:YCPrintCellIdentify];
    
    m_headerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kMainScreen_Width, 110)];
    
    UIView *backView=[[UIView alloc]initWithFrame:CGRectMake(kDistance, kDistance, width, 90)];
    [backView setBackgroundColor:WHITE_COLOR];
    backView.layer.cornerRadius=2.0f;
    
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(kDistance, 10, 100, 20)];
    [label setText:@"已连接"];
    [label setFont:[UIFont LightFontOfSize:14]];
    [label setTextColor:TEXT_LIGHT];
    [backView addSubview:label];
    
    UIImageView *lineView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 36, width, 8)];
    [lineView setImage:[UIImage imageNamed:@"comment_line"]];
    [backView addSubview:lineView];
    [backView addShadow];
    
    m_selectedBtn=[[UIButton alloc]initWithFrame:CGRectMake(kDistance, 40, width-2*kDistance, 50)];
    m_selectedBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
    [m_selectedBtn setTitle:@"GPrinter_FC8C" forState:UIControlStateNormal];
    [m_selectedBtn setImage:[UIImage imageNamed:@"print_selected"] forState:UIControlStateNormal];
    [m_selectedBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -32, 0, 16)];
    [m_selectedBtn setImageEdgeInsets:UIEdgeInsetsMake(17, W(m_selectedBtn)-16, 17, 0)];
    [m_selectedBtn setTitleColor:TEXT_DEEP forState:UIControlStateNormal];
    [m_selectedBtn.titleLabel setFont:[UIFont LightFontOfSize:16]];
    [backView addSubview:m_selectedBtn];
    
    [m_headerView addSubview:backView];
    m_tableView.tableHeaderView=nil;
    
}
-(void)btnSelectedClicked:(UIButton *)button
{
    [m_selectedBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    
}
#pragma mark tableview datasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

#pragma mark tableview delegate
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kSmallDistance;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kMainScreen_Width, kSmallDistance)];
    [header setBackgroundColor:WHITE_COLOR];
    return header;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height=40+_deviceArray.count*50+10;
    return height;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier=@"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (nil == cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    
     YCPrintTableViewCell *_cell = (YCPrintTableViewCell *)[tableView dequeueReusableCellWithIdentifier:YCPrintCellIdentify forIndexPath:indexPath];
    _cell.deviceArray=_deviceArray;
    [_cell bind];
    _cell.connectBlock=^(CBPeripheral *peripheral,BOOL connected){
        if (connected) {
            NSString *uuidStr=peripheral.identifier.UUIDString;
            
            NSUserDefaults  *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setValue:uuidStr forKey:@"uuidstring"];
            [userDefault setValue:@"yes" forKey:@"printOn"];
            
            [[SEPrinterManager sharedInstance] connectPeripheral:peripheral completion:^(CBPeripheral *perpheral, NSError *error) {
                if (error) {
                    [self.view showHUD:@"连接失败"];
                } else {
                    self.title = @"已连接";
                    [self.view showHUD:@"连接成功"];
                    [m_selectedBtn setTitle:peripheral.name forState:UIControlStateNormal];
                    m_tableView.tableHeaderView=m_headerView;
                    
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstPrint"];
                    [[SEPrinterManager sharedInstance]stopScan];
                    self.connectedDevices=[NSMutableArray arrayWithObject:peripheral];
                    [m_tableView reloadData];
                }
            }];
        }else{
            [[SEPrinterManager sharedInstance]cancelPeripheral:peripheral];
            [self.connectedDevices removeObject:peripheral];
            m_tableView.tableHeaderView=nil;
            NSUserDefaults  *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setValue:@"" forKey:@"uuidstring"];
            if (self.connectBlock) {
                self.connectBlock();
            }
            [self loadDevices];
        }
    };
    cell=_cell;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
